/**
 * @Author      : xingnan
 * @Email       : 457415936@qq.com
 * @Time        : 16:45
 * @File        : daemonize.go
 * @Project     : toolbox
 * @Description : 守护进程
 */
package com

import (
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

// AppIsRunningEx daemon is running
func AppIsRunningEx(pidfile string) (int, error) {
	line, err := ReadFileFirstLine(pidfile)
	if err != nil {
		return 0, err
	}
	pidstr := strings.TrimSpace(line)
	pid, err := strconv.Atoi(pidstr)
	if err != nil {
		return 0, err
	}
	if err := processIsRunning(pid); err != nil {
		return 0, err
	}
	return pid, nil
}

// AppImmobilized pid
func AppImmobilized(pidfile string) error {
	piddir := filepath.Dir(pidfile)
	if _, err := os.Stat(piddir); err != nil && os.IsNotExist(err) {
		if err = os.MkdirAll(piddir, 0775); err != nil {
			return err
		}
	}
	file, err := os.Create(pidfile)
	if err != nil {
		return err
	}
	defer file.Close()
	if _, err := file.WriteString(strconv.Itoa(os.Getpid())); err != nil {
		return err
	}
	return nil
}
